package com.sam.designpattern.adapter;

import java.io.*;
import java.util.List;

/**
 * @Author: Sam
 * @Date: 2022-07-21 17:55
 * @Description: 实现对日志文件的操作
 */
public class LogFileOperate implements LogFileOperateApi {

    /**
     * 日志文件的路径和文件名称，默认是当前项目根目录下的logs/AdapterLog.log
     */
    private String logFilePathName = "logs/AdapterLog.log";

    public LogFileOperate(String logFilePathName) {
        if (logFilePathName != null && logFilePathName.trim().length() > 0) {
            this.logFilePathName = logFilePathName;
        }
    }

    @Override
    public List<LogModel> readLogFile() {
        List<LogModel> list = null;

        File f = new File(logFilePathName);
        if (f.exists()) {
            try (ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f)))) {
                list = (List<LogModel>) oin.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    @Override
    public void writeLogFile(List<LogModel> list) {
        File f = new File(logFilePathName);
        try (ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(f)))) {
            oout.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
